/*
    Copyright (C) 2021 Huawei Device Co., Ltd.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.danikula.videocache;

import com.danikula.videocache.bean.ProgressBean;
import com.danikula.videocache.interfacers.CacheListener;

import java.io.File;
import java.util.List;

/**
 * 缓存策略(目前分为默认缓存 分文件缓存  单文件断点缓存)
 * 不同缓存所需的配置参数通过本地传入进去
 */
public abstract class CacheStrategy {
    /**
     * 初始化当前缓存文件
     *
     * @param config 配置信息
     * @param url    视频url
     * @return 当前缓存文件
     */
    protected File generateCacheFile(Config config, String url) {
        String name = config.fileNameGenerator.generate(url);
        return new File(config.cacheRoot, name);
    }

    /**
     * 生成缓存管理对象
     *
     * @param source          视频信息下载Source
     * @param config          配置信息
     * @param uiCacheListener 缓存进度监听器
     * @param url             视频url
     * @return 缓存管理对象
     * @throws ProxyCacheException 生成代理对象错误
     */
    protected abstract ProxyCache createHttpProxyCache(HttpUrlSource source, Config config,
    CacheListener uiCacheListener, String url) throws ProxyCacheException;

    /**
     * 将已下载区域转化为分段显示进度条的进度区域
     *
     * @param fileLength   文件总长度
     * @param downLoadArea 已下载区域
     * @param initData     进度条的进度区域初始值
     */
    protected void transDownloadAreaToProgress(long fileLength, List<long[]> downLoadArea,
    List<ProgressBean> initData) {
        // 结合视频文件总长度 将文件缓存区域转化为进度范围
        for (int i = 0; i < downLoadArea.size(); i++) {
            long[] longs = downLoadArea.get(i);
            long start = longs[0];
            long end = longs[1];
            long startProgress = start * 100 / fileLength;
            int startPer = (int) (start * 100 % fileLength == 0 ? startProgress : startProgress + 1);
            long endProgress = end * 100 / fileLength;
            int endPer = (int) (end * 100 % fileLength == 0 ? endProgress : endProgress + 1);
            if (startPer <= 0) {
                startPer = 0;
            }
            if (endPer <= 0) {
                endPer = 0;
            }
            if (endPer > 100) {
                endPer = 100;
            }
            for (int j = 0; j < initData.size(); j++) {
                if (j >= startPer && j <= endPer) {
                    ProgressBean bean = initData.get(j);
                    bean.setDefault(false);
                    initData.set(j, bean);
                }
            }
        }
    }

}
